// Package repository
/**
* @Project : geektime-basic-go-study
* @File    : code.go
* @IDE     : GoLand
* @Author  : Tvux
* @Date    : 2024/10/5 12:22
**/

package repository

import (
	"context"
	"geektime-basic-go-study/webook/backend/internal/repository/cache"
)

// CodeRepository 定义了验证码存储和验证操作的接口。
type CodeRepository interface {
	// Store 将验证码存储到缓存中。
	Store(ctx context.Context, biz string, phone string, code string) error
	// Verify 验证给定的验证码是否正确。
	Verify(ctx context.Context, biz string, phone string, code string) (bool, error)
}

var (
	ErrCodeSendTooMany   = cache.ErrCodeSendTooMany
	ErrCodeVerifyTooMany = cache.ErrCodeVerifyTooMany
)

var (
	_ CodeRepository = (*CachedCodeRepository)(nil)
)

type CachedCodeRepository struct {
	cc cache.CodeCache
}

func (Self *CachedCodeRepository) Store(ctx context.Context, biz string, phone string, code string) error {
	return Self.cc.Set(ctx, biz, phone, code)
}

func (Self *CachedCodeRepository) Verify(ctx context.Context, biz string, phone string, code string) (bool, error) {
	return Self.cc.Verify(ctx, biz, phone, code)
}

func NewCachedCodeRepository(cc cache.CodeCache) CodeRepository {
	return &CachedCodeRepository{
		cc: cc,
	}
}
